package com.qianli.user.domain.respository;

import com.fqgj.xjd.user.dao.UserQuotaDao;
import com.fqgj.xjd.user.entity.UserQuotaEntity;
import com.google.common.collect.Lists;
import com.qianli.user.domain.enums.UserModelItemStatusEnum;
import com.qianli.user.domain.model.UserQuotaModel;
import com.qianli.user.domain.model.quota.UserQuota;
import com.qianli.user.enums.QuotaEnum;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * name:用户额度
 * auth:ting.li@qianli-inc.com
 * date:2018/1/3 20:12
 * version: v1.0.0
 **/
@Repository
public class UserQuotaRespsitory implements BaseRespository<UserQuotaModel> {

    @Autowired
    private UserQuotaDao userQuotaDao;

    /**
     * 加载额度
     * @param model
     */
    @Override public void load(UserQuotaModel model) {
        List<UserQuota> userQuotas = Lists.newArrayList();
        List<UserQuotaEntity> quotaEntities = userQuotaDao.getAllQutoaByuserCode(model.getUserCode());
        if (CollectionUtils.isNotEmpty(quotaEntities)) {
            for (UserQuotaEntity entity : quotaEntities) {
                UserQuota quota = new UserQuota();
                BeanUtils.copyProperties(entity, quota);
                quota.setGmtModified(entity.getGmtModified());
                quota.setQuotaEnum(QuotaEnum.getEnumByType(entity.getStatus()));
                userQuotas.add(quota);
            }
        }
        model.setUserQuotas(userQuotas);
    }
    /**
     * 保存额度
     * @param model
     */
    @Override
    public void store(UserQuotaModel model) {
        UserQuota userQuota = model.getUserQuotas().get(0);
        UserQuotaEntity entity = new UserQuotaEntity();
        BeanUtils.copyProperties(userQuota, entity);
        entity.setStatus(userQuota.getQuotaEnum().getType());
        if (userQuota.getItemStatus().equals(UserModelItemStatusEnum.ADD.getType())) {
            userQuotaDao.insert(entity);
        } else if (userQuota.getItemStatus().equals(UserModelItemStatusEnum.UPDATE.getType())) {
            userQuotaDao.updateByPrimaryKey(entity);
        }
    }

    @Override
    public void restore(UserQuotaModel model) {

    }

}
